package com.oe.rpc.core.listeners;

import com.oe.rpc.context.IRpcListener;
import com.oe.rpc.context.RpcContext;
import com.oe.rpc.context.RpcEvent;
import com.oe.rpc.core.events.TryConnectEvent;
import com.oe.rpc.network.IClient;
import com.oe.rpc.network.NettyClient;
import com.oe.rpc.register.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class TryConnectListener implements IRpcListener<TryConnectEvent> {

    private static Logger logger = LoggerFactory.getLogger(TryConnectListener.class);


    @Override
    public Object excute(RpcEvent rpcEvent) {

        List<ServiceInfo> services = (List<ServiceInfo>) rpcEvent.getSource();

        for (ServiceInfo service : services) {
            IClient client = RpcContext.getInstance().getClient(service.getUrl());
            if(null==client || !client.isActive()){
                String[] url = service.getUrl().split(":");
                client=new NettyClient(url[0],Integer.parseInt(url[1]));
                //加上等待客户端连接等待和重连接的逻辑
                int connectTimes=3;
                int waitTimes=5;
                while(!client.isActive() && connectTimes>0){
                    client.connect();
                    while (!client.isActive() && waitTimes>0){
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        waitTimes--;
                    }
                    if(client.isActive()){
                        break;
                    }
                    connectTimes--;
                    waitTimes=5;
                }
                if(client.isActive()){
                    logger.info("成功连接服务：{}",service.getUrl());
                    RpcContext.getInstance().cacheClient(service.getUrl(),client);
                    break;
                }else {
                    logger.info("cannot connect to server:{}",service.getUrl());
                }

            }else {
                continue;
            }
        }

        return "SUCCESS";
    }
}
